package com.mytrip.webapp.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map.Entry;

import com.mytrip.base.action.StrutsActionAdapter;
import com.mytrip.model.City;
import com.mytrip.model.FlightCity;
import com.mytrip.model.Trip;
import com.mytrip.model.TripNotifyUser;
import com.mytrip.model.TripPlan;
import com.mytrip.model.TripPlanFlight;
import com.mytrip.model.TripPlanHotel;
import com.mytrip.model.TripPlanMeeting;
import com.mytrip.model.TripPlanNote;
import com.mytrip.model.Userinfo;
import com.mytrip.service.TripManager;
import com.mytrip.util.Caches;
import com.mytrip.util.PageInfo;
import com.mytrip.util.UploadUtil;
import com.mytrip.webapp.filter.CtxSessionBag;

public class FrontTripAction extends StrutsActionAdapter{

	private static final long serialVersionUID = -1284846469238942959L;

	private TripManager tripManager;

	private Trip trip;

	private PageInfo<Trip> page = new PageInfo<Trip>();

	private List<TripPlan> planList;

	private File uploadPic;

	private String uploadPicFileName;

	private int nextCnt;

	private int historyCnt;

	private int draftCnt;

	// ~ method =================================================================

	public String goAdd() throws Exception{
		trip = Trip.emptyOne();

		return "goAdd";
	}

	public String goEdit() throws Exception{
		String editId = getRequest().getParameter("editId");

		trip = tripManager.queryTripById(Integer.parseInt(editId));
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		if (!Trip.STATUS_DRAFT.equals(trip.getTripStatus())) {
			throw new Exception("trip status is not draft");
		}

		trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
		trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
		trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));

		// FIXME check permission,获得页面通知的用户

		return "goEdit";
	}

	public String addTrip() throws Exception{
		Integer tid = tripManager.addTrip(trip);

		String isTravler = trip.getIsTraveler();
		if ("1".equals(isTravler)) {
			Userinfo userinfo = CtxSessionBag.getSessionBag().getUserinfo();
			TripNotifyUser notify = new TripNotifyUser();
			notify.setEmail(userinfo.getEmail());
			notify.setMobile(userinfo.getMobile());
			notify.setTid(tid);
			notify.setUserName(userinfo.getRealName());
			tripManager.saveTripNotifyUser(notify);
		}

		// FIXME check permission,页面添加的需要通知的用户
		trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
		trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
		trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));

		planList = tripManager.queryTripPlanByTrip(trip.getId());

		return "managePlan";
	}

	public String editTrip() throws Exception{
		tripManager.editTrip(trip);

		// 清空通知用户
		tripManager.clearTripNotifyUserByTripId(trip.getId());

		String isTravler = trip.getIsTraveler();
		if ("1".equals(isTravler)) {
			Userinfo userinfo = CtxSessionBag.getSessionBag().getUserinfo();
			TripNotifyUser notify = new TripNotifyUser();
			notify.setEmail(userinfo.getEmail());
			notify.setMobile(userinfo.getMobile());
			notify.setTid(trip.getId());
			notify.setUserName(userinfo.getRealName());
			tripManager.saveTripNotifyUser(notify);
		}

		// FIXME check permission,页面添加的需要通知的用户
		trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
		trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
		trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));

		planList = tripManager.queryTripPlanByTrip(trip.getId());

		return "managePlan";
	}

	public String tripPic() throws Exception{
		String editId = getRequest().getParameter("editId");
		if (editId == null) {
			trip = Trip.emptyOne();
		} else {
			trip = tripManager.queryTripById(Integer.parseInt(editId));
			if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
				throw new Exception("permission error");
			}

			trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
			trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
			trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));

			// FIXME check permission,获得页面通知的用户
		}

		String picPath = UploadUtil.uploadTripPic(uploadPic, uploadPicFileName);
		trip.setPhoto(picPath);
		return SUCCESS;
	}

	public String showNextTrip(){
		cnt();
		page.setUrl(getRequest().getContextPath() + "/front/trip!showNextTrip.action");
		page.setAllSize(nextCnt);
		page.setDataList(tripManager.queryNextTrip(page.getFrom(), page.getPageSize()));
		for (Trip trip : page.getDataList()) {
			trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
			trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
			trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));
		}
		return "showNextTrip";
	}

	public String showHistoryTrip(){
		cnt();
		page.setUrl(getRequest().getContextPath() + "/front/trip!showHistoryTrip.action");
		page.setAllSize(historyCnt);
		page.setDataList(tripManager.queryHistoryTrip(page.getFrom(), page.getPageSize()));
		for (Trip trip : page.getDataList()) {
			trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
			trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
			trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));
		}
		return "showHistoryTrip";
	}

	public String showDraftTrip(){
		cnt();
		page.setUrl(getRequest().getContextPath() + "/front/trip!showDraftTrip.action");
		page.setAllSize(draftCnt);
		page.setDataList(tripManager.queryDraftTrip(page.getFrom(), page.getPageSize()));
		for (Trip trip : page.getDataList()) {
			trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
			trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
			trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));
		}
		return "showDraftTrip";
	}

	private void cnt(){
		nextCnt = tripManager.queryNextTripCnt();
		historyCnt = tripManager.queryHistoryTripCnt();
		draftCnt = tripManager.queryDraftTripCnt();
	}

	public String detail() throws Exception{
		String id = getRequest().getParameter("id");
		trip = tripManager.queryTripById(Integer.parseInt(id));
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
		trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
		trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));

		planList = tripManager.queryTripPlanByTrip(trip.getId());
		return "detail";
	}

	public String print() throws Exception{
		String id = getRequest().getParameter("id");
		trip = tripManager.queryTripById(Integer.parseInt(id));
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		trip.setFromCityStr(tripManager.queryCityById(trip.getFromCity()).getName());
		trip.setToCityStr(tripManager.queryCityById(trip.getToCity()).getName());
		trip.setNotifyUserList(tripManager.queryNotifyUserByTrip(trip.getId()));

		planList = tripManager.queryTripPlanByTrip(trip.getId());
		return "print";
	}

	public String delete() throws Exception{
		String id = getRequest().getParameter("id");
		trip = tripManager.queryTripById(Integer.parseInt(id));
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		tripManager.deleteTrip(trip);
		getRequest().setAttribute("t", "2");
		cnt();
		return "opInfo";
	}

	public String finish() throws Exception{
		String id = getRequest().getParameter("id");
		trip = tripManager.queryTripById(Integer.parseInt(id));
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		tripManager.finishTrip(trip);
		getRequest().setAttribute("t", "1");
		cnt();
		return "opInfo";
	}

	public String addFlightPlan(Integer tid, String flightTime, String arriveTime, String airline, String flightNumber,
			String fromPort, String toPort) throws Exception{
		trip = tripManager.queryTripById(tid);
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		TripPlanFlight flight = new TripPlanFlight();
		flight.setFlightTime(sdf.parse(flightTime));
		flight.setArriveTime(sdf.parse(arriveTime));
		flight.setAirline(airline);
		flight.setFlightNumber(flightNumber);

		flight.setFromPort(fromPort);
		boolean tf1 = false;
		for (Entry<Integer, List<FlightCity>> e : Caches.cityPorts.entrySet()) {
			if (tf1) {
				break;
			}
			for (FlightCity fc : e.getValue()) {
				if (fromPort.equalsIgnoreCase(fc.getCity3code())) {
					flight.setFromCity(e.getKey());
					tf1 = true;
					break;
				}
			}
		}

		flight.setToPort(toPort);
		boolean tf2 = false;
		for (Entry<Integer, List<FlightCity>> e : Caches.cityPorts.entrySet()) {
			if (tf2) {
				break;
			}
			for (FlightCity fc : e.getValue()) {
				if (toPort.equalsIgnoreCase(fc.getCity3code())) {
					flight.setToCity(e.getKey());
					tf2 = true;
					break;
				}
			}
		}

		TripPlan plan = new TripPlan();
		plan.setTid(tid);
		plan.setType(TripPlan.TYPE_FLIGHT);
		plan.setFlight(flight);

		Integer id = tripManager.addPlan(plan);

		String fromCityCn = "";
		if (flight.getFromCity() != null) {
			for (City c : Caches.cityList) {
				if (c.getId().equals(flight.getFromCity())) {
					fromCityCn = c.getName();
					break;
				}
			}
		}

		String toCityCn = "";
		if (flight.getToCity() != null) {
			for (City c : Caches.cityList) {
				if (c.getId().equals(flight.getToCity())) {
					toCityCn = c.getName();
					break;
				}
			}
		}

		return id + "," + fromCityCn + "," + toCityCn;
	}

	public Integer addHotelPlan(Integer tid, String checkInTime, String checkOutTime, String address, String roomName,
			String hotelName) throws Exception{
		trip = tripManager.queryTripById(tid);
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		TripPlanHotel hotel = new TripPlanHotel();
		hotel.setCheckInTime(sdf.parse(checkInTime));
		hotel.setCheckOutTime(sdf.parse(checkOutTime));
		hotel.setAddress(address);
		hotel.setRoomName(roomName);
		hotel.setHotelName(hotelName);

		TripPlan plan = new TripPlan();
		plan.setTid(tid);
		plan.setType(TripPlan.TYPE_HOTEL);
		plan.setHotel(hotel);

		Integer id = tripManager.addPlan(plan);
		return id;
	}

	public Integer addMeetingPlan(Integer tid, String meetingTime, String meetingInfo) throws Exception{
		trip = tripManager.queryTripById(tid);
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		TripPlanMeeting meeting = new TripPlanMeeting();
		meeting.setMeetingTime(sdf.parse(meetingTime));
		meeting.setMeetingInfo(meetingInfo);

		TripPlan plan = new TripPlan();
		plan.setTid(tid);
		plan.setType(TripPlan.TYPE_MEETING);
		plan.setMeeting(meeting);

		Integer id = tripManager.addPlan(plan);
		return id;
	}

	public Integer addNotePlan(Integer tid, String noteStr, String noteTime) throws Exception{
		trip = tripManager.queryTripById(tid);
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		TripPlanNote note = new TripPlanNote();
		note.setNote(noteStr);
		note.setNoteTime(sdf.parse(noteTime));

		TripPlan plan = new TripPlan();
		plan.setTid(tid);
		plan.setType(TripPlan.TYPE_NOTE);
		plan.setNote(note);

		Integer id = tripManager.addPlan(plan);
		return id;
	}

	public boolean delPlan(Integer pid) throws Exception{
		TripPlan plan = tripManager.queryPlanById(pid);
		Integer tid = plan.getTid();
		trip = tripManager.queryTripById(tid);
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		tripManager.deletePlan(plan);
		return true;
	}
	
	public boolean notifyPlan(Integer pid,Boolean ckd) throws Exception{
		TripPlan plan = tripManager.queryPlanById(pid);
		Integer tid = plan.getTid();
		trip = tripManager.queryTripById(tid);
		if (!trip.getUid().equals(CtxSessionBag.getSessionBag().getUserinfo().getId())) {
			throw new Exception("permission error");
		}

		tripManager.notifyPlan(plan,ckd);
		return true;
	}
	
	public String queryCityWeather(Integer cityId){
		return tripManager.queryCityWeather(cityId);
	}

	public void setTripManager(TripManager tripManager){
		this.tripManager = tripManager;
	}

	public Trip getTrip(){
		return trip;
	}

	public void setTrip(Trip trip){
		this.trip = trip;
	}

	public File getUploadPic(){
		return uploadPic;
	}

	public void setUploadPic(File uploadPic){
		this.uploadPic = uploadPic;
	}

	public String getUploadPicFileName(){
		return uploadPicFileName;
	}

	public void setUploadPicFileName(String uploadPicFileName){
		this.uploadPicFileName = uploadPicFileName;
	}

	public int getNextCnt(){
		return nextCnt;
	}

	public void setNextCnt(int nextCnt){
		this.nextCnt = nextCnt;
	}

	public int getHistoryCnt(){
		return historyCnt;
	}

	public void setHistoryCnt(int historyCnt){
		this.historyCnt = historyCnt;
	}

	public int getDraftCnt(){
		return draftCnt;
	}

	public void setDraftCnt(int draftCnt){
		this.draftCnt = draftCnt;
	}

	public PageInfo<Trip> getPage(){
		return page;
	}

	public void setPage(PageInfo<Trip> page){
		this.page = page;
	}

	public List<TripPlan> getPlanList(){
		return planList;
	}

	public void setPlanList(List<TripPlan> planList){
		this.planList = planList;
	}

}
